package com.example.hans.databaseandroid;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import tools.AnalysisUtils;
import tools.CutPictureUtils;
import tools.OkHttpUtil;

public class SplashActivity extends AppCompatActivity implements OkHttpUtil.OnNeedSendMessageInterface{
    private TextView tv_version;
    private ImageView iv_background;
    private ProgressDialog progressDialog;

    private OkHttpUtil mOkHttpUtil = new OkHttpUtil(this);
    private final static int FAIL = 0;
    private Bitmap bitmap = null;
//    private CutPictureUtils cutPictureUtils = new CutPictureUtils(SplashActivity.this);

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FAIL: {
                    Toast.makeText(SplashActivity.this, "网络出现了问题", Toast.LENGTH_SHORT).show();
                    break;
                }
                case 1: {
                    byte[] Picture = (byte[]) msg.obj;
                    bitmap = BitmapFactory.decodeByteArray(Picture,0,Picture.length);
                    iv_background.setImageBitmap(bitmap);
                    break;
                }
                case 2: {
                    String strImgALL = (String)msg.obj;
                    praseJSONWithGSON(strImgALL);
                    break;
                }
                default:
                    super.handleMessage(msg);
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        //设置为此界面为竖屏（因为是欢迎界面）
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        init();
    }

    private void init(){
        tv_version= findViewById(R.id.tv_version);
        iv_background=findViewById(R.id.iv_background1);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        // 如果想加入时分秒，pattern设为"yyyy年MM月dd日 HH:mm:ss"
        Date date = new Date(System.currentTimeMillis());
//        String fileName = simpleDateFormat.format(date) + ".jpg";
//        Uri imgUri= Uri.parse("file:///sdcard/crazystudy/"+ fileName);
//        if(AnalysisUtils.isFolderExists("/sdcard/crazystudy/")){
//            if (AnalysisUtils.fileIsExists(imgUri.getPath())){
//                // 显示出来
//                Log.d("yes","yes");
//                iv_background.setImageBitmap(cutPictureUtils.decodeUriAsBitmap(imgUri));
//            }else {
//                Log.d("yes","no");
//                //获取bing背景图片
//                imgUri = Uri.parse("https://img2.woyaogexing.com/2017/10/21/1d94513768a421ae!600x600.jpg");
//                iv_background.setImageBitmap(cutPictureUtils.decodeUriAsBitmap(imgUri));
//            }
//        } else {
//            Log.d("yes","no1");
//        }
        mOkHttpUtil.getOkHttpBitmap("https://img2.woyaogexing.com/2017/10/21/1d94513768a421ae!600x600.jpg");

        try{
            //获取程序包信息
            PackageInfo info=getPackageManager().getPackageInfo(getPackageName(),0);
            tv_version.setText("欢迎来到小信"+info.versionName);
        }catch (PackageManager.NameNotFoundException e){
            tv_version.setText("欢迎来到小信");
        }
        //让此界面延迟3秒后再跳转，timer中有一个线程，这个线程不断执行task
        Timer timer = new Timer();
        //TimerTask类表示一个在指定时间内执行的task
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                //打开后判断是否是登录状态，如果是，则自动登录
                SharedPreferences sp = getSharedPreferences("loginInfo",MODE_PRIVATE);
                boolean isLogin=sp.getBoolean("isLogin",false);
                Intent intent;
                if (isLogin){
                    Intent data = new Intent();
                    data.putExtra("isLogin",true);
                    setResult(RESULT_OK,data);
                    intent=new Intent(SplashActivity.this,LoginActivity.class);
                }else {
                    intent=new Intent(SplashActivity.this,MainActivity.class);
                }
                startActivity(intent);
                SplashActivity.this.finish();
            }
        };
        timer.schedule(task,3000);      //设置这个task在延迟2秒之后自动执行
    }


    //使用GSON解析json数据
    private void praseJSONWithGSON(String jsonData) {
        //先转JsonObject
        JsonObject jsonObject = new JsonParser().parse(jsonData).getAsJsonObject();
        //再转JsonArray 加上数据头
        JsonArray jsonArray = jsonObject.getAsJsonArray("images");

        Gson gson = new Gson();
//        ArrayList<Image> imgList = new ArrayList<>();

        //循环遍历
        for (JsonElement user : jsonArray) {
            //通过反射 得到UserBean.class
//            Image img = gson.fromJson(user, new TypeToken<Image>() {}.getType());
//            img.setCopyright(img.getCopyright());
//            mImageList.add(img);


//            imgList.add(img);
//            System.out.println(img.getUrl() + "-------------");
//            System.out.println(img.getCopyright() + "-------------");
        }


//        BingYingPic bingYingPic = new Gson().fromJson(jsonData, BingYingPic.class);
//        System.out.println(bingYingPic + "-------------");
//        for (int i = 0; i < bingYingPic.images.size(); i++) {
//            System.out.println(bingYingPic.images.get(i).bingBasePicUrl + "-------------");
//            System.out.println(bingYingPic.images.get(i).endDate + "-------------");
//        }

    }

    @Override
    public void OnNeedSendMessageForStr(String str) {
        Message message = new Message();
        message.what = 2;
        message.obj = str;
        mHandler.sendMessage(message);
    }

    @Override
    public void OnNeedSendMessageForBytes(byte[] bytes) {
        Message msg = new Message();
        msg.what = 1;
        msg.obj = bytes;
        mHandler.sendMessage(msg);
    }

    @Override
    public void OnNeedSendMessageForFAll() {
        mHandler.sendEmptyMessage(FAIL);
    }
}
